//
//  HPGoodsDetailsScrollView.m
//  fruitsDealers
//
//  Created by sgone on 16/4/21.
//  Copyright © 2016年 com.sgone. All rights reserved.
//

#import "HPGoodsDetailsScrollView.h"
#import "UIImageView+WebCache.h"
#import "FDInquiryView.h"
#import "Common.h"
#import "labelAdaptive.h"
#import "UIView+Helper.h"
#import "FDLineView.h"
@interface HPGoodsDetailsScrollView () <UIWebViewDelegate> {
    
    NSArray *lineArray;
    UIView *bgView;
    UIImageView *imgView;
}

/**
 *水果图片
 */
@property (nonatomic, strong)UIImageView *goodsImageView;
/**
 *水果名称
 */
@property (nonatomic, strong)UILabel *nameLabel;
/**
 *水果单位
 */
@property (nonatomic, strong)UILabel *unitLabel;
/**
 *水果价格
 */
@property (nonatomic, strong)UILabel *priceLabel;
/**
 *水果规格
 */
@property (nonatomic, strong)UILabel *formLabel;
/**
 *水果分类
 */
@property (nonatomic, strong)UILabel *categoryLabel;
/**
 *水果产地
 */
@property (nonatomic, strong)UILabel *locationLabel;
/**
 *水果起批量
 */
@property (nonatomic, strong)UILabel *startOrderLabel;
/**
 *水果简介
 */
//@property (nonatomic, strong)UITextView *descriptionTextView;
@property (nonatomic, strong)UIWebView *descriptionWebView;
/**
 *中间的背景view
 */
@property (nonatomic, strong)UIView *backView;

@end

@implementation HPGoodsDetailsScrollView

- (UIImageView *)goodsImageView {
    
    if (_goodsImageView == nil) {
        
        _goodsImageView = [[UIImageView alloc] init];
        _goodsImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:_goodsImageView];
    }
    return _goodsImageView;
}

- (UILabel *)nameLabel {
    
    if (_nameLabel == nil) {
        
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = FDFont_COLOR;
        _nameLabel.font = [UIFont systemFontOfSize:16 / FDLaOt];
        [self addSubview:_nameLabel];
    }
    return _nameLabel;
}

- (UILabel *)unitLabel {
    
    if (_unitLabel == nil) {
        
        _unitLabel = [[UILabel alloc] init];
        _unitLabel.textColor = FDMainColorAla;
        _unitLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_unitLabel];
    }
    return _unitLabel;
}

- (UILabel *)priceLabel {
    
    if (_priceLabel == nil) {
        
        _priceLabel = [[UILabel alloc] init];
        _priceLabel.textColor = FDMFont_COLOR;
        _priceLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_priceLabel];
    }
    return _priceLabel;
}

- (UILabel *)formLabel {
    
    if (_formLabel == nil) {
        
        _formLabel = [[UILabel alloc] init];
        _formLabel.textColor = FDFont_COLOR;
        _formLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_formLabel];
    }
    return _formLabel;
}

- (UILabel *)categoryLabel {
    
    if (_categoryLabel == nil) {
        
        _categoryLabel = [[UILabel alloc] init];
        _categoryLabel.textColor = FDFont_COLOR;
        _categoryLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_categoryLabel];
    }
    return _categoryLabel;
}

- (UILabel *)locationLabel {
    
    if (_locationLabel == nil) {
        
        _locationLabel = [[UILabel alloc] init];
        _locationLabel.textColor = FDFont_COLOR;
        _locationLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_locationLabel];
    }
    return _locationLabel;
}

- (UILabel *)startOrderLabel {
    
    if (_startOrderLabel == nil) {
        
        _startOrderLabel = [[UILabel alloc] init];
        _startOrderLabel.textColor = FDFont_COLOR;
        _startOrderLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
        [self addSubview:_startOrderLabel];
    }
    return _startOrderLabel;
}

- (UIView *)backView {
    
    if (_backView == nil) {
        
        _backView = [[UILabel alloc] init];
        _backView.backgroundColor = FDBack_COLOR;
        [self addSubview:_backView];
    }
    return _backView;
}

//- (UITextView *)descriptionTextView {
//    
//    if (_descriptionTextView == nil) {
//        
//        _descriptionTextView = [[UITextView alloc] init];
//        _descriptionTextView.textColor = FDGFont_COLOR;
//        _descriptionTextView.font = [UIFont systemFontOfSize:14 / FDLaOt];
//        _descriptionTextView.userInteractionEnabled = NO;
//        [self addSubview:_descriptionTextView];
//    }
//    return _descriptionTextView;
//}

- (UIWebView *)descriptionWebView
{
    if (_descriptionWebView == nil) {
        _descriptionWebView = [[UIWebView alloc] init];
        _descriptionWebView.dataDetectorTypes = UIDataDetectorTypeAll;
        _descriptionWebView.delegate = self;
        [self addSubview:_descriptionWebView];
    }
    return _descriptionWebView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        
    }
    return self;
}

+ (instancetype)initWithFrame:(CGRect)frame {
    
    return [[self alloc] initWithFrame:frame];
}

- (void)setMessageDic:(NSDictionary *)messageDic {
    
    
    
    
    _messageDic = messageDic;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
    
    for (NSString *key in [dic allKeys]) {
        
        if ([checkNull(dic[key]) length] == 0) {
            
            [dic removeObjectForKey:key];
            [dic setValue:@"" forKey:key];
        }
    }
    
  
    
    [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"images"]] placeholderImage:[UIImage imageNamed:@"backGround"]];
    
   
    self.nameLabel.text = dic[@"title"];

    
    NSString *priceUnit = nil;
    
    switch ([dic[@"price_unit"] integerValue]) {
        case 1:
            priceUnit = @"斤";
            break;
        case 2:
            priceUnit = @"公斤";
            break;
        case 3:
            priceUnit = @"箱";
            break;
            
        default:
            break;
    }
    
    self.unitLabel.text = [NSString stringWithFormat:@"%.2f元/%@",[dic[@"price"] floatValue],priceUnit];
    
//    self.priceLabel.text = [];
    NSString *startOrderUnit = nil;
    
    switch ([dic[@"least_unit"] integerValue]) {
        case 1:
            startOrderUnit = @"斤";
            break;
        case 2:
            startOrderUnit = @"公斤";
            break;
        case 3:
            startOrderUnit = @"箱";
            break;
            
        default:
            break;
    }
    
    self.formLabel.text = [NSString stringWithFormat:@"规格：%@",startOrderUnit];
    
    
    
    
    self.categoryLabel.text = [NSString stringWithFormat:@"%@：%@",dic[@"cat_name"],dic[@"p_cat_name"]];
    
    self.locationLabel.text = [NSString stringWithFormat:@"产地：%@",dic[@"place_name"]];
    
    self.startOrderLabel.text = [NSString stringWithFormat:@"起订量：%.2f%@",[dic[@"least_number"] floatValue],startOrderUnit];
    
//    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[dic[@"content"] dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
//    self.descriptionTextView.attributedText = attrStr;
    [self.descriptionWebView loadHTMLString:dic[@"content"] baseURL:nil];
}

- (CGFloat)setViewsFrameAndReturnHeight {
    
    self.goodsImageView.frame = CGRectMake(0, 0, self.width, self.width);
    self.backView.frame = CGRectMake(0, self.goodsImageView.height, self.goodsImageView.width, 20 / FDLaOt);
//     NSLog(@"sdahsjdahs  %f",self.goodsImageView.frame);
    CGFloat X = 16;
    CGFloat Y = 8;
    
    CGSize nameSize = [labelAdaptive sizeWithString:self.nameLabel.text font:self.nameLabel.font];
    self.nameLabel.frame = CGRectMake(X, self.backView.y + self.backView.height + Y, self.width - X * 2, nameSize.height);
    
    CGSize unitSize = [labelAdaptive sizeWithString:self.unitLabel.text font:self.unitLabel.font];
    self.unitLabel.frame = CGRectMake(X, self.nameLabel.y + self.nameLabel.height + Y, unitSize.width, unitSize.height);
    
    CGSize priceSize = [labelAdaptive sizeWithString:self.priceLabel.text font:self.priceLabel.font];
    self.priceLabel.frame = CGRectMake(self.unitLabel.x + self.unitLabel.width + X, self.unitLabel.y, priceSize.width, unitSize.height);
    
    CGSize formSize = [labelAdaptive sizeWithString:self.formLabel.text font:self.formLabel.font];
    self.formLabel.frame = CGRectMake(X, self.unitLabel.y + self.unitLabel.height + Y * 2, formSize.width, formSize.height);
    
    CGSize categorySize = [labelAdaptive sizeWithString:self.categoryLabel.text font:self.categoryLabel.font];
    self.categoryLabel.frame = CGRectMake(self.width / 2 + X, self.formLabel.y, categorySize.width, categorySize.height);
    
    CGSize locationSize = [labelAdaptive sizeWithString:self.locationLabel.text font:self.locationLabel.font];
    self.locationLabel.frame = CGRectMake(X, self.formLabel.y + self.formLabel.height + Y * 2, self.width / 2 - X * 4, locationSize.height);
    
    CGSize startOrderSize = [labelAdaptive sizeWithString:self.startOrderLabel.text font:self.startOrderLabel.font];
    self.startOrderLabel.frame = CGRectMake(self.width / 2 + X, self.locationLabel.y, startOrderSize.width, startOrderSize.height);
    
//    CGFloat textViewHeight = [self heightForString:self.descriptionTextView.attributedText fontSize:14 / FDLaOt andWidth:self.width - X * 2];
//    self.descriptionTextView.frame = CGRectMake(X, self.locationLabel.y + self.locationLabel.height + Y * 2, self.width - X * 2, textViewHeight);
//
    
//    self.descriptionWebView.frame = CGRectMake(X, self.locationLabel.y + self.locationLabel.height + Y * 2, self.width - X * 2, self.height);
    lineArray = @[self.goodsImageView,self.unitLabel,self.formLabel,self.locationLabel];
    
    for (int i = 0; i < lineArray.count; i ++) {
        
        FDLineView *lineView;
        
        if (i == 0) {
            
            lineView = [[FDLineView alloc] initWithFrame:CGRectMake(0, [lineArray[i] frame].origin.y + [lineArray[i] frame].size.height, self.width, 0.5)];
        } else {
            
            lineView = [[FDLineView alloc] initWithFrame:CGRectMake(0, [lineArray[i] frame].origin.y + [lineArray[i] frame].size.height + Y, self.width, 0.5)];
        }
        [self addSubview:lineView];
    }
    
    return self.descriptionWebView.y + self.descriptionWebView.height + 50 / FDLaOt;
}

- (CGFloat)heightForString:(NSAttributedString *)value fontSize:(float)fontSize andWidth:(float)width {
    
    UITextView *detailTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
    detailTextView.font = [UIFont systemFontOfSize:fontSize];
    detailTextView.attributedText = value;
    CGSize deSize = [detailTextView sizeThatFits:CGSizeMake(width,CGFLOAT_MAX)];
    
    return deSize.height;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    webView.frame = CGRectMake(0, self.locationLabel.y + self.locationLabel.height + 8 * 2, self.width, self.height / 3);
    
//    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '95%'";
//    [webView stringByEvaluatingJavaScriptFromString:str];
//    
    //js方法遍历图片添加点击事件 返回图片个数
//    static  NSString * const jsGetImages =
//    @"function getImages(){\
//    var objs = document.getElementsByTagName(\"img\");\
//    for(var i=0;i<objs.length;i++){\
//    objs[i].onclick=function(){\
//    document.location=\"myweb:imageClick:\"+this.src;\
//    };\
//    };\
//    return objs.length;\
//    };";
//    
//    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
//    
//    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
//    NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    //调用js方法
    //    NSLog(@"---调用js方法--%@  %s  jsMehtods_result = %@",self.class,__func__,resurlt);
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    CGRect frame = webView.frame;
    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height + 20 / FDLaOt);
    
//    webView.frame = CGRectMake(0, self.locationLabel.y + self.locationLabel.height + 8 * 2, self.width, height);
    
    if ([checkNull(self.messageDic[@"content"]) length] == 0) {
        
        self.contentSize = CGSizeMake(ViewWidth, self.locationLabel.y + self.locationLabel.height + 50 / FDLaOt);
    } else
        self.contentSize = CGSizeMake(ViewWidth, self.descriptionWebView.y + webView.height + 50 / FDLaOt);
}

//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    //将url转换为string
//    NSString *requestString = [[request URL] absoluteString];
//    //    NSLog(@"requestString is %@",requestString);
//    
//    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
//    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
//        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
//        //        NSLog(@"image url------%@", imageUrl);
//        
//        if (bgView) {
//            //设置不隐藏，还原放大缩小，显示图片
//            bgView.hidden = NO;
//            imgView.frame = CGRectMake(10, 10, FDSCREEN_WIDTH-40, 220);
//            [imgView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"backGround"]];
//        }
//        else
//            [self showBigImage:imageUrl];//创建视图并显示图片
//        
//        return NO;
//    }
//    return YES;
//}

//-(void)showBigImage:(NSString *)imageUrl{
//    //创建灰色透明背景，使其背后内容不可操作
//    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FDSCREEN_WIDTH, FDSCREEN_HEIGHT)];
//    [bgView setBackgroundColor:[UIColor colorWithRed:0.3
//                                               green:0.3
//                                                blue:0.3
//                                               alpha:0.7]];
//    [self.superview addSubview:bgView];
//    
//    //创建边框视图
//    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FDSCREEN_WIDTH-20, 240)];
//    //将图层的边框设置为圆脚
//    borderView.layer.cornerRadius = 8;
//    borderView.layer.masksToBounds = YES;
//    //给图层添加一个有色边框
//    borderView.layer.borderWidth = 8;
//    borderView.layer.borderColor = [[UIColor colorWithRed:0.9
//                                                    green:0.9
//                                                     blue:0.9
//                                                    alpha:0.7] CGColor];
//    [borderView setCenter:bgView.center];
//    [bgView addSubview:borderView];
//    
//    //创建关闭按钮
//    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    //    [closeBtn setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
//    closeBtn.backgroundColor = [UIColor redColor];
//    [closeBtn addTarget:self action:@selector(removeBigImage) forControlEvents:UIControlEventTouchUpInside];
//    [closeBtn setFrame:CGRectMake(borderView.frame.origin.x+borderView.frame.size.width-20, borderView.frame.origin.y-6, 26, 27)];
//    [bgView addSubview:closeBtn];
//    
//    //创建显示图像视图
//    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(borderView.frame)-20, CGRectGetHeight(borderView.frame)-20)];
//    imgView.userInteractionEnabled = YES;
//    imgView.contentMode = UIViewContentModeScaleAspectFit;
//    [imgView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"backGround"]];
//    [borderView addSubview:imgView];
//    
//    //添加捏合手势
//    [imgView addGestureRecognizer:[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)]];
//    
//}
//
////关闭按钮
//-(void)removeBigImage
//{
//    bgView.hidden = YES;
//}
//
//- (void)handlePinch:(UIPinchGestureRecognizer*) recognizer
//{
//    //缩放:设置缩放比例
//    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
//    recognizer.scale = 1;
//}

@end
